package com.generalsentiment.evaluation

import java.io.IOException
import java.io.PrintWriter
import java.io.File
import scala.util.parsing.json._
import scala.io.Source

class SingleTest(sourceFile: File) extends SentimentTest {

  private val inputLines = Source.fromFile(sourceFile).getLines
  private val examples = inputLines.map(new SingleExample(_))

  def makeQueries(destination: File): Unit = {
    val output = new PrintWriter(new File(destination, sourceFile.getName()))
    examples.foreach(_.makeQueries(output))
    output.close()
  }
}

class SingleExample(lineToParse: String) {
  private val tokens = lineToParse.split("\t")
  private val entity = tokens(0)
  private val jsonMap = JSON.parseFull(tokens(1))

  def makeQueries(output: PrintWriter): Unit = {
    output.println(entity + "\t" + datesAsJSON(jsonMap));
  }

  def datesAsJSON(parsedJSON: Option[Any]): String = parsedJSON match {
    case someMap: Some[Map[String, Any]] => iterAsJSON(someMap.get.map(_._1))
    case _ => throw new IOException("Improper JSON type.  Object expected: " + parsedJSON)
  }

  def iterAsJSON(iter: Iterable[String]): String = {
    "[" + iter.mkString(",") + "]"
  }
}
